var express = require('express');
var router = express.Router();
const shsDB = require("../../db/index.js");
const addOperationLog = require('./../../utils/operationLog/index.js'); 
//查询群聊的用户信息
router.get('/userlist', function(req, res, next) {
	try {
		if (!req.query.userlist) {
			res.send(JSON.stringify({
				code: 400,
				message: "参数不合法[userlist]"
			}));
			return;
		}
		let sql =
			`select Id,username,url,gender,status from users where Id in (${trimTrailingComma(req.query.userlist)})`;
		shsDB(sql).then(data => {
			res.send(JSON.stringify({
				code: 200,
				data,
				message: "success"
			}))
		}).catch(err => {
			res.send(JSON.stringify({
				code: 500,
				message: err.message
			}))
		})
	} catch (error) {
		res.send(JSON.stringify({
			code: 500,
			message: error.message
		}))
	}

})
//修改群聊头像
router.post('/updateGroupUrl',  jwtVerify,function(req, res, next) {
	try {
		if (!req.body.url || !req.body.Id) {
			res.send(JSON.stringify({
				code: 400,
				message: "参数不合法[url,Id]"
			}));
			return;
		}
	} catch (error) {
		res.send(JSON.stringify({
			code: 500,
			message: error.message
		}))
	}
	let sql = `update shsgroup set url='${req.body.url}' where Id='${req.body.Id}'`
	shsDB(sql).then(data => {
		if (data.affectedRows > 0) {
			updateRelation(req.body.Id, {
				code:"updateGroup",
				flag:"updateGroupUrl",
				Id: req.body.Id,
				otherUrl: req.body.url
			})
			res.send(JSON.stringify({
				code: 200,
				Id: req.body.Id,
				otherUrl: req.body.url,
				message: "修改成功"
			}))
			addOperationLog(req.shsImUserInfo.fromId, '修改群聊头像', 'shsgroup', req.body.Id, null, req.body.url)
		} else {
			res.send(JSON.stringify({
				code: 500,
				message: "修改失败"
			}))
		}
	}).catch(err => {
		res.send(JSON.stringify({
			code: 400,
			message: "修改失败"
		}))
	})
})
//修改群聊名称
router.post('/updateGroupName',  jwtVerify, function(req, res, next) {
	try {
		if (!req.body.username || !req.body.Id) {
			res.send(JSON.stringify({
				code: 400,
				message: "参数不合法[username,Id]"
			}));
			return;
		}
	} catch (error) {
		res.send(JSON.stringify({
			code: 500,
			message: error.message
		}))
	}
	let sql = `update shsgroup set groupname='${req.body.username}' where Id='${req.body.Id}'`
	shsDB(sql).then(data => {
		if (data.affectedRows > 0) {
			// 推送 全部端更新列表
			updateRelation(req.body.Id, {
				code:"updateGroup",
				flag:"updateGroupName",
				Id: req.body.Id,
				otherName: req.body.username
			})
			res.send(JSON.stringify({
				code: 200,
				Id: req.body.Id,
				otherName: req.body.username,
				message: "修改成功"
			}))
			addOperationLog(req.shsImUserInfo.fromId, '修改群聊名称', 'shsgroup', req.body.Id, null, req.body.username)
		} else {
			res.send(JSON.stringify({
				code: 500,
				message: "修改失败"
			}))
		}
	}).catch(err => {
		res.send(JSON.stringify({
			code: 500,
			message: "修改失败"
		}))
	})
})
//退出群聊 用户ID 群聊ID 群聊成员id
router.post('/exit', function(req, res, next) {
	try {
		if (!req.body.userId || !req.body.Id) {
			res.send(JSON.stringify({
				code: 400,
				message: "参数不合法[userId,Id,userlist]"
			}));
			return;
		} else if (!req.body.userlist) {
			res.send(JSON.stringify({
				code: 400,
				message: "系统群聊，无法退出！"
			}));
			return;
		}
		let newUserlist = removeNumberIfExists(req.body.userlist, req.body.userId)
		let sql = `update shsgroup set userlist='${newUserlist}' where Id='${req.body.Id}'`
		shsDB(sql).then(data => {
			if (data.affectedRows > 0) {
				// 推送 全部端更新列表
				updateRelation(req.body.Id, {
					groupId: req.body.Id,
					userlist: newUserlist,
					code:"exit",
					exitUserId:req.body.userId
				})
				//推送自己的设备端
				WSsendMessage({
					type: 99,
					groupId: req.body.Id,
					code:"exit",
					exitUserId:req.body.userId
				}, req.body.userId)
				res.send(JSON.stringify({
					code: 200,
					groupId: req.body.Id,
					message: "退出成功"
				}))
				addOperationLog(req.body.userId, '退出群聊', 'shsgroup', req.body.Id, req.body.userlist, newUserlist)
			} else {
				res.send(JSON.stringify({
					code: 500,
					message: "退出失败"
				}))
			}
		}).catch(err => {
			res.send(JSON.stringify({
				code: 500,
				message: "退出失败"
			}))
		})
	} catch (error) {
		res.send(JSON.stringify({
			code: 500,
			message: error.message
		}))
	}

})

/**推送群聊信息 type99 
@param {string}Id 群聊
@param {string} data 发送数据
*/
function updateRelation(Id, data) {
	try {
		let sql = "select userlist from shsgroup where Id= " + Id;
		shsDB(sql).then(res => {
			if (res[0].userlist) {
				let arr = res[0].userlist.split(',')
				for (let i = 0; i < arr.length; i++) {
					// 给指定id发送数据
					WSsendMessage({
						type: 99,
						...data
					}, arr[i])
				}
			}
		})
	} catch (error) {
		console.log("error", error);
	}
}
/**检查字符串是否为空或者不是以逗号结尾 str
@param {string} str 
@returns str
*/
function trimTrailingComma(str) {
	// 检查字符串是否为空或者不是以逗号结尾
	if (!str || str.slice(-1) !== ',') {
		return str;
	}
	// 去掉最后一个逗号
	return str.slice(0, -1);
}

function removeNumberIfExists(userlist, numberToRemove) {
	let numberStr = numberToRemove.toString();

	let regexPattern = new RegExp(`\\b${numberStr}\\b`, 'g');

	let modifiedUserlist = userlist.replace(regexPattern, '');

	modifiedUserlist = modifiedUserlist.replace(/,{2,}/g, ',').trim();
	if (modifiedUserlist.endsWith(',')) {
		modifiedUserlist = modifiedUserlist.slice(0, -1);
	}
	if (modifiedUserlist.startsWith(',')) {
		modifiedUserlist = modifiedUserlist.slice(1);
	}

	return modifiedUserlist;
}



module.exports = router;